package com.aqie.appletserver.controller.tencentapi;

import com.aqie.appletserver.bean.VoiceList;
import com.aqie.appletserver.bean.request.TencentVoiceTranslateRequest;
import com.aqie.appletserver.bean.response.TencentVoiceTranslateResponse;
import com.aqie.appletserver.common.response.ResponseModel;
import com.aqie.appletserver.service.ITencentApiService;
import com.aqie.appletserver.service.IUploadService;
import com.aqie.appletserver.service.IVoiceListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("tencent")
public class TencentController {

    @Autowired
    private IUploadService uploadService;

    @Autowired
    private ITencentApiService tencentApiService;

    @Autowired
    private IVoiceListService voiceListService;

    @PostMapping("voiceTranslate")
    public ResponseModel<TencentVoiceTranslateResponse>
        voiceTranslate(@RequestParam("file") MultipartFile files,
                       HttpServletRequest request, String openId) throws IOException {
        TencentVoiceTranslateRequest voiceTranslateRequest = new TencentVoiceTranslateRequest();
        Map<String, String> resMap = uploadService.uploadAudio(request, files);
        TencentVoiceTranslateResponse response = tencentApiService.voiceTranslate(voiceTranslateRequest, resMap.get("localSavePath"));
        saveVoiceToDatabase(openId, resMap, response);

        return ResponseModel.success(response);
    }

    private void saveVoiceToDatabase(String openId, Map<String, String> resMap, TencentVoiceTranslateResponse response) {
        // 保存用户openid 地址 设备信息 到数据库
        VoiceList voiceList = new VoiceList();
        voiceList.setCreateTime((int) (System.currentTimeMillis() / 1000));
        voiceList.setOpenid(openId);
        voiceList.setVoice_url(resMap.get("databaseSavePath"));
        voiceList.setContent(response.getData().getSourceText());
        voiceList.setFroms("tencent");
        voiceList.setTransContent(response.getData().getTargetText());
        voiceListService.save(voiceList);
    }

}
